// e33.groovy
@Grab(group='commons-math', module='commons-math', version='1.2')
/*
The fraction 49/98 is a curious fraction, as an inexperienced mathematician in attempting to simplify it may incorrectly believe that 49/98 = 4/8, which is correct, is obtained by cancelling the 9s.

We shall consider fractions like, 30/50 = 3/5, to be trivial examples.

There are exactly four non-trivial examples of this type of fraction, less than one in value, and containing two digits in the numerator and denominator.

If the product of these four fractions is given in its lowest common terms, find the value of the denominator.
*/
def equals(f1, f2) {
    def delta = 0.0000001
    def val = Math.abs(f1 - f2)
    val <= delta
}

def isCurious(num, den) {
    def decval = num / den
    def n1 = num / 10 as int
    def n2 = num % 10 as int
    def d1 = den / 10 as int
    def d2 = den % 10 as int
    if (d2 == 0) return false
    if (n1 == n2 || d1 == d2) return false
    (n2 == d2 && equals(decval, n1 / d1)) ||
    (n1 == d2 && equals(decval, n2 / d1)) ||
    (n2 == d1 && equals(decval, n1 / d2)) ||
    (n1 == d1 && equals(decval, n2 / d2))
}

results = []
for (n in 10..98) {
    for (d in (n + 1)..99) {
        if (isCurious(n, d)) results << [n, d]
    }
}
println "The non-trivial fractions are: "
results.each { println "\t${it[0]}/${it[1]}" }

print "The denominator of the product of these fractions is: "
product = results.inject(1) { product, fraction -> fraction[0] / fraction[1] * product }
println new org.apache.commons.math.fraction.Fraction(product).denominator
